package org.example.day11;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 4.1.13.3 lock.tryLock(3, TimeUnit.SECONDS) 尝试获取锁，获取不到最多等待3秒，期间获得锁返回true，3秒后仍获取不到返回false.
 **/
public class MyThread17 {
    public ReentrantLock lock = new ReentrantLock();
    public void waitMethod(){
        try {
            if(lock.tryLock(3, TimeUnit.SECONDS)){
                System.out.println("Threadname = " + Thread.currentThread().getName() + " 获取锁的时间: " + System.currentTimeMillis());
                Thread.sleep(1000);
            }else {
                System.out.println(Thread.currentThread().getName() + "没有获取锁,时间: " + System.currentTimeMillis());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        final MyThread17 m17 = new MyThread17();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("Threadname = " + Thread.currentThread().getName() + " 调用waitMethod的时间: " + System.currentTimeMillis());
                m17.waitMethod();
            }
        };
        Thread ta = new Thread(runnable);
        ta.setName("A");
        ta.start();
        Thread tb = new Thread(runnable);
        tb.setName("B");
        tb.start();
    }
}
